package de.hdu.myjobapp.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import de.hdu.myjobapp.model.Application;
import de.hdu.myjobapp.model.Organisation;
import de.hdu.myjobapp.model.Rating;
import de.hdu.myjobapp.model.User;

public class RatingDao extends HibernateDaoSupport{

	/**
	 * create a new Rating
	 */	
	public void create(Organisation orgId, Application applicationId, String keyWord, Integer ratingGrad){
		Rating r = new Rating();
		r.setOrgId(orgId);
		r.setApplicationId(applicationId);
		r.setKeyWord(keyWord);
		r.setRatingGrad(ratingGrad);
		save(r);
	}
	

		

	/**
	 * Saves the new recieved Rating from Method create with hibernate into database
	 */	
	public Rating save(Rating rating){
		HibernateTemplate template = getHibernateTemplate();
		template.saveOrUpdate(rating);
		return rating;
	}


	/**
	 * return all existing Rating
	 */	
	public List<Rating> findAll(){
		HibernateTemplate template = getHibernateTemplate();
		return template.loadAll(Rating.class);
	}

	/**
	 * Return an existing Rating by naming ID
	 */	
	public Rating findById(int id){
		HibernateTemplate template = getHibernateTemplate();
		return(Rating) template.get(Rating.class, id);
	}
	/**
	 * Find all ratings related to a specific Application
	 * TODO - improve process not to read whole sql table
	 */
	public List<Rating> findAll(Application application){
		HibernateTemplate template = getHibernateTemplate();
		List<Rating> applicationRatings = new ArrayList<Rating>();
		List<Rating> allratings = template.loadAll(Rating.class);
		for(Rating rating:allratings){
			if(rating.getApplicationId().getApplicationId().equals(application.getApplicationId())){
				
				applicationRatings.add(rating);
			}
		}
		return applicationRatings;
	}
	/**
	 * Method to delete a Rating created by a User
	 * TODO secure the process - check if it is the users object
	 * @param rating Rating to delete
	 */
	public void delete(Rating rating) {
		HibernateTemplate template = getHibernateTemplate();
		template.delete(rating);
	}
}
